package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import cn.sharesdk.framework.ShareSDK;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

import com.baidu.mapapi.SDKInitializer;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.jakewharton.salvage.RecyclingPagerAdapter;
import com.kingtone.rongji.biz.Region;
import com.kingtone.rongji.db.DataBaseOpenHelper;
import com.kingtone.rongji.db.RegionDao;
import com.kingtone.rongji.fragment.DashboardFragment.MyOnPageChangeListener;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.ListUtils;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * Splash���棬����ݵĳ�ʼ���ȹ���
 * 
 * @author Administrator
 * 
 */
public class SplashActivity extends Activity {

	private static final String TAG = "SplashActivity";

	private AutoScrollViewPager viewPager;
	
	private LinearLayout dotsView;

	private Context context;

	private LayoutInflater mInflater = null;
	
	private List<ImageView>     dotsItemView;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		context = this;
		this.setContentView(R.layout.activity_splash);
		mInflater = (LayoutInflater) this.getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		viewPager = (AutoScrollViewPager) this.findViewById(R.id.id_splash);
		dotsView  = (LinearLayout) this.findViewById(R.id.dots);
		initDataForLaunch();
	}

	@Override
	public void onResume() {
		super.onResume();
		boolean isLaunched = SharedPreferencesUtil.getInstance(this)
				.getBoolean(AppContasts.FIRSTLAUNCH);
		if (isLaunched) {
			new Handler().postDelayed(new Runnable(){
				@Override
				public void run() {
					// TODO Auto-generated method stub
					goToHome();
				}
				
			}, 1400);
		} else {
			ViewPagerAdapter adapter = new ViewPagerAdapter(this);
			viewPager.setAdapter(adapter);
			viewPager.setCycle(false);
			viewPager.setInterval(3000);
			viewPager.startAutoScroll();
			viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
			
			dotsItemView = new ArrayList<ImageView>(4);
			dotsView.removeAllViews();
	        ImageView dotItem;
			for (int i = 0; i < 4; i++) {
				dotItem = new ImageView(this);
				dotItem.setImageResource(R.drawable.dot);
				dotsItemView.add(dotItem);
				dotsView.addView(dotItem);
			}
			setCurrentDotItem(0);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		viewPager.stopAutoScroll();
	}
	
	private void setCurrentDotItem(int index) {
		if(null == dotsItemView) {
			return;
		}
		
		if(index>-1 && index<dotsItemView.size()) {
			for(int i=0;i<dotsItemView.size();i++) {
				if(index==i) {
					dotsItemView.get(i).setImageResource(R.drawable.dot_pressed);
				} else {
					dotsItemView.get(i).setImageResource(R.drawable.dot);
				}
			}
		}
	}
	
	private void initDataForLaunch() {
		Log.d(TAG, "initDataForLaunch");
		boolean regionLoaded = SharedPreferencesUtil.getInstance(context)
				.getBoolean(AppContasts.IS_ALERY_LOAD_REGION);
		if (!regionLoaded) {
			initRegions();
		}
	}

	private void goToHome() {
		SharedPreferencesUtil.getInstance(this).putBoolean(
				AppContasts.FIRSTLAUNCH, true);
		Intent intent = new Intent(this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	
	public class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
        	setCurrentDotItem(position);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    }
	
	class ViewPagerAdapter extends RecyclingPagerAdapter {

		private DisplayImageOptions mOptions;

		private Context context;

		public ViewPagerAdapter(Context context) {
			this.context = context;
			mOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
					.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565)
					.delayBeforeLoading(100).build();
		}

		@Override
		public int getCount() {
			return 4;
		}

		@Override
		public View getView(int position, View view, ViewGroup container) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (view == null) {
				holder = new ViewHolder();
				view = mInflater
						.inflate(R.layout.splash_item, container, false);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			holder.imageView = (ImageView) view.findViewById(R.id.imageContent);
			holder.button = (Button) view.findViewById(R.id.enterButton);
			holder.imageView.setOnClickListener(null);
			switch (position) {
			case 0:
				holder.imageView.setImageResource(R.drawable.img1);
				holder.button.setVisibility(View.GONE);
				break;
			case 1:
				holder.imageView.setImageResource(R.drawable.img2);
				holder.button.setVisibility(View.GONE);
				break;
			case 2:
				holder.imageView.setImageResource(R.drawable.img3);
				holder.button.setVisibility(View.GONE);
				break;
			case 3:
				holder.imageView.setImageResource(R.drawable.img4);
				holder.button.setVisibility(View.VISIBLE);
				holder.button.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						goToHome();
					}
				});
				break;
			default:
				break;
			}
			return view;
		}

		class ViewHolder {
			ImageView imageView;
			Button button;
		}
	}

	// 获取省信息
	private void initRegions() {
		RongJiRestClient.getRegionAll(new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				if (arg2 != null && !new String(arg2).equalsIgnoreCase("null")) {
					String result = new String(arg2);
					Gson gson = new Gson();
					JsonParser parser = new JsonParser();
					JsonElement element = parser.parse(result);
					if (element instanceof JsonArray) {
						JsonArray array = element.getAsJsonArray();
						List<Region> regions = new ArrayList<Region>();
						for (JsonElement obj : array) {
							Region region = gson.fromJson(obj, Region.class);
							regions.add(region);
						}
						RegionDao dao = new RegionDao(context);
						dao.addRegionsToDB(regions);
						SharedPreferencesUtil.getInstance(context).putBoolean(
								AppContasts.IS_ALERY_LOAD_REGION, true);
					}
				}
			}
		});
	}
}
